
class _ApiService {
  constructor() {
    this.base_url = 'https://live.chinatravelacademy.com'
  }

  get(url, data = {}) {
    return this.request(url, 'GET', JSON.stringify(data))
  }

  post(url, data = {}) {
    return this.request(url, 'POST', JSON.stringify(data))
  }

  upload(url, data) {
    return this.request(url, 'POST', data)
  }

  _request(url, method, _data, success, fail, complete) {
    let xhr = new XMLHttpRequest()
    xhr.open(method, `${this.base_url}${url}`, true)
    xhr.setRequestHeader('accept', 'application/json')
    xhr.onreadystatechange = function() {
      if(xhr.readyState == 4) {
        if(xhr.status == 200) {
          let res = {}
          try {
            res = JSON.parse(xhr.response)
            success && success(res)
          } catch(e) {
            if (url.indexOf('type=user-token') >= 0) {
              res = {status: true, data: {token: xhr.response}}
              success && success(res)
            } else {
              fail && fail()
            }

          }
        } else {
          fail && fail()
        }
        complete && complete()
      }
    }
    let data = null
    if (_data) {
      data = _data
    }
    if (!(data instanceof FormData)) {
      xhr.setRequestHeader('Content-Type', 'application/json');
    }
    xhr.send(data)
  }

  request(url, method, data) {
    return new Promise((resolve, reject) => {
      this._request(url, method, data, (res) => {
        resolve(res)
      }, () => {
        reject(new Error('http error'))
      })
    })
  }

  getPrizeResult(pool_id, token) {
    return this.get(`/live/room/prize/pool/${pool_id}?__token=${token}`)
  }
}

const ApiService = new _ApiService()
export default ApiService
